package ch15;

/**
 * Created by hasee on 2017/10/18.
 */

import java.util.Iterator;

public class CircularArrayQueue<T> implements Queue<T>
{
    private final int DEFAULT_CAPACITY = 100;
    private int front, rear, count;
    private T[] queue;

    public CircularArrayQueue()
    {
        front = rear = count = 0;
        queue = (T[]) (new Object[DEFAULT_CAPACITY]);
    }

    public void enqueue (T element)
    {
        if (size() == queue.length)
            expandCapacity();

        queue[rear] = element;
        rear = (rear+1) % queue.length;

        count++;
    }

    public void expandCapacity()
    {
        T[] larger = (T[])(new Object[queue.length *2]);

        for(int scan=0; scan < count; scan++)
        {
            larger[scan] = queue[front];
            front=(front+1) % queue.length;
        }

        front = 0;
        rear = count;
        queue = larger;
    }
    public T dequeue()
    {
        if (count==0)
        {System.out.println("Error.");
        return null;}
        else {
        T result = queue[front];
        count = count-1;
        queue[front]=null;
        front=front+1;
        return result;}

    }


    public T first()
    {
        if (count==0)
            System.out.println("Error.");
        return queue[count - 1];
    }


    public boolean isEmpty()
    {
        if (count==0)
        return true;
        else
            return false;
    }


    public int size()
    {
        return count;
    }


    public String toString()
    {
        String result = "";
        for (int index = count - 1; index >= 0; index--)
            result += queue[index] +" ";
        return result ;
        }


    }


